#!/usr/bin/env node
/**
 * 字段规范验证和纠正工具
 * 用于检查方案文档中的字段定义是否符合PB系统规范，并自动纠正错误
 *
 * 使用方法：
 * node scripts/validate-and-correct-fields.js <方案文档路径>
 *
 * 输出：
 * 1. 验证报告（控制台）
 * 2. 纠正后的方案文档（-corrected.md）
 * 3. 详细的纠正报告（-correction-report.json）
 */

const fs = require('fs');
const path = require('path');

// ========== 规则库定义 ==========

/**
 * 字段命名映射规则
 * 用于纠正常见的命名错误
 */
const FIELD_NAME_MAPPING = {
  // 背景相关
  backgroundColor: 'bgColor',
  backgroundColorOpacity: 'bgColorOpacity',
  backgroundImage: 'bgImg',
  hasBackground: 'hasBg',

  // 标题相关
  titleFontColor: 'titleColor',
  titleSize: 'titleFontSize',

  // 静态文本
  staticTextColor: 'staticTitleFontColor',
  staticTextSize: 'staticTitleFontSize',

  // 边距相关
  marginTop: 'topMargin',
  marginBottom: 'bottomMargin',
  marginHorizontal: 'horizontalOutterMargin',
  paddingTop: 'topPadding',
  paddingBottom: 'bottomPadding',
  paddingHorizontal: 'horizontalInnerPadding',

  // 其他常见错误
  showMoreButton: 'showMore',
  titleBarVisible: 'showTitleBar',
  borderRadius: 'cornerRadius',
  moreButtonText: 'moreText',
  jumpUrl: 'jumpLink',
};

/**
 * 字段数据类型规则
 * 定义每个字段的正确数据类型
 */
const FIELD_TYPE_RULES = {
  // Boolean类型（显示控制）
  visible: { type: 'boolean', default: true },
  showTitle: { type: 'boolean', default: true },
  showMore: { type: 'boolean', default: true },
  showTitleBar: { type: 'boolean', default: true },
  showDesc: { type: 'boolean', default: true },
  closable: { type: 'boolean', default: false },

  // Y/N类型（样式控制）
  isTitleFontBold: { type: 'Y|N', default: 'Y' },
  isTitleFontItalic: { type: 'Y|N', default: 'N' },
  isTitleFontUnderline: { type: 'Y|N', default: 'N' },
  isStaticTitleFontBold: { type: 'Y|N', default: 'N' },
  isStaticTitleFontItalic: { type: 'Y|N', default: 'N' },
  hasBg: { type: 'Y|N', default: 'N' },
  needLogin: { type: 'Y|N', default: 'N' },
  allowUserEdit: { type: 'Y|N', default: 'N' },

  // 图片数组类型
  titleIcon: {
    type: 'imageArray',
    structure: '[{src: "", width: 0, height: 0, iconName: "", link: "", linkId: "", linkType: ""}]',
  },
  moreIcon: {
    type: 'imageArray',
    structure: '[{src: "", width: 0, height: 0, iconName: "", link: "", linkId: "", linkType: ""}]',
  },
  leftIcon: {
    type: 'imageArray',
    structure: '[{src: "", width: 0, height: 0, iconName: "", link: "", linkId: "", linkType: ""}]',
  },
  pictures: {
    type: 'imageArray',
    structure: '[{src: "", width: 0, height: 0, iconName: "", link: "", linkId: "", linkType: ""}]',
  },

  // 背景图对象类型
  bgImg: {
    type: 'imageObject',
    structure: '{src: "", width: 0, height: 0}',
  },
  dashboardBgImg: {
    type: 'imageObject',
    structure: '{src: "", width: 0, height: 0}',
  },

  // 字符串类型（颜色）
  bgColor: { type: 'string', default: '#ffffff' },
  titleColor: { type: 'string', default: '#242424' },
  moreColor: { type: 'string', default: '#6A52E8' },
  staticTitleFontColor: { type: 'string', default: '#545454' },
  borderColor: { type: 'string', default: '#e6e6e6' },
  selectedTabColor: { type: 'string', default: '#6A52E8' },
  chartLineColor: { type: 'string', default: '#6A52E8' },
  chartAreaColor: { type: 'string', default: 'rgba(106, 82, 232, 0.1)' },
  tooltipBackgroundColor: { type: 'string', default: 'rgba(0, 0, 0, 0.8)' },
  tooltipTextColor: { type: 'string', default: '#FFFFFF' },
  gridLineColor: { type: 'string', default: '#D9D9D9' },
  labelColor: { type: 'string', default: '#545454' },
  contentFontColor: { type: 'string', default: '#242424' },
  subtitleColor: { type: 'string', default: '#545454' },
  primaryColor: { type: 'string', default: '#6A52E8' },

  // 数字类型（透明度）
  bgColorOpacity: { type: 'number', default: 100 },
  titleColorOpacity: { type: 'number', default: 100 },
  titleFontColorOpacity: { type: 'number', default: 100 },
  moreColorOpacity: { type: 'number', default: 100 },
  staticTitleFontColorOpacity: { type: 'number', default: 100 },
  borderColorOpacity: { type: 'number', default: 100 },
  chartLineColorOpacity: { type: 'number', default: 100 },
  chartAreaColorOpacity: { type: 'number', default: 20 },
  tooltipBackgroundColorOpacity: { type: 'number', default: 100 },
  gridLineColorOpacity: { type: 'number', default: 100 },
  labelColorOpacity: { type: 'number', default: 100 },
  contentFontColorOpacity: { type: 'number', default: 100 },
  subtitleColorOpacity: { type: 'number', default: 100 },
  primaryColorOpacity: { type: 'number', default: 100 },

  // 字符串类型（尺寸）
  titleFontSize: { type: 'string', default: '16' },
  titleFontWeight: { type: 'string', default: '600' },
  titleLineHeight: { type: 'string', default: '24' },
  moreFontSize: { type: 'string', default: '14' },
  staticTitleFontSize: { type: 'string', default: '14' },
  topMargin: { type: 'string', default: '0' },
  bottomMargin: { type: 'string', default: '0' },
  horizontalOutterMargin: { type: 'string', default: '0' },
  topPadding: { type: 'string', default: '16' },
  bottomPadding: { type: 'string', default: '16' },
  horizontalInnerPadding: { type: 'string', default: '16' },
  cornerRadius: { type: 'string', default: '8' },
  borderRadius: { type: 'string', default: '8' },

  // 枚举类型
  bgType: { type: 'enum', values: ['Color', 'Image'], default: 'Color' },
  quickTemplate: { type: 'enum', values: ['white', 'purple'], default: 'white' },
  titleIconPosition: { type: 'enum', values: ['L', 'R'], default: 'L' },
  titlePosition: { type: 'enum', values: ['left', 'center', 'right'], default: 'left' },
  chartTheme: { type: 'enum', values: ['White', 'Black'], default: 'White' },

  // 数字类型
  displayMonths: { type: 'number', default: 6 },
  maxTabCount: { type: 'number', default: 4 },

  // 数组类型
  enabledBalanceTypes: { type: 'array', default: ['Voice', 'SMS', 'Data'] },
  groupSetting: { type: 'array', default: [] },
  profileSetting: { type: 'array', default: [] },

  // 对象类型
  balanceTypeLabels: { type: 'object', default: {} },
  androidValue: { type: 'object', default: { miniVersion: '', maxVersion: '' } },
  iosValue: { type: 'object', default: { miniVersion: '', maxVersion: '' } },

  // 字符串类型（普通）
  title: { type: 'string', default: 'Usage Trends at Last 6 Months' },
  moreText: { type: 'string', default: 'More' },
  jumpLink: { type: 'string', default: '' },
  defaultActiveTab: { type: 'string', default: '' },
  targetLabel: { type: 'string', default: '' },
  floorName: { type: 'string', default: '' },
  publishTime: { type: 'string', default: '' },
  expireTime: { type: 'string', default: '' },
  configureMode: { type: 'string', default: '' },
  containerWidth: { type: 'string', default: 'auto' },
};

/**
 * 字段配套规则
 * 定义哪些字段必须成对出现
 */
const FIELD_PAIRING_RULES = {
  // 颜色必须配透明度
  bgColor: ['bgColorOpacity'],
  titleColor: ['titleColorOpacity', 'titleFontColorOpacity'],
  moreColor: ['moreColorOpacity'],
  staticTitleFontColor: ['staticTitleFontColorOpacity'],
  borderColor: ['borderColorOpacity'],
  selectedTabColor: ['selectedTabColorOpacity'],
  chartLineColor: ['chartLineColorOpacity'],
  chartAreaColor: ['chartAreaColorOpacity'],
  tooltipBackgroundColor: ['tooltipBackgroundColorOpacity'],
  gridLineColor: ['gridLineColorOpacity'],
  labelColor: ['labelColorOpacity'],
  contentFontColor: ['contentFontColorOpacity'],
  subtitleColor: ['subtitleColorOpacity'],
  primaryColor: ['primaryColorOpacity'],

  // 字体配样式
  titleFontSize: ['isTitleFontBold', 'isTitleFontItalic', 'isTitleFontUnderline'],
  staticTitleFontSize: ['isStaticTitleFontBold', 'isStaticTitleFontItalic'],

  // 背景配套
  hasBg: ['bgType', 'bgColor', 'bgColorOpacity'],

  // 链接配套
  jumpLink: ['jumpLinkType', 'jumpLinkId'],
  moreLink: ['moreLinkType', 'moreLinkId'],
};

/**
 * Content章节的必需公共字段
 * 根据600_BIZ规范，这些字段必须在Content可配置内容下
 */
const REQUIRED_CONTENT_FIELDS = {
  // Header面板 - 可见性控制
  visible: { type: 'boolean', default: true, belongTo: 'header', section: 'content' },

  // Event Report Setting面板
  floorName: { type: 'string', default: '', belongTo: 'eventReportSetting', section: 'content' },

  // Group Setting面板 - Visibility Rules
  groupSetting: { type: 'array', default: [], belongTo: 'groupSetting', section: 'content' },
  profileSetting: { type: 'array', default: [], belongTo: 'groupSetting', section: 'content' },
  targetLabel: { type: 'string', default: '', belongTo: 'groupSetting', section: 'content' },
  needLogin: { type: 'Y|N', default: 'N', belongTo: 'groupSetting', section: 'content' },
  androidValue: {
    type: 'object',
    default: { miniVersion: '', maxVersion: '' },
    belongTo: 'groupSetting',
    section: 'content',
  },
  iosValue: {
    type: 'object',
    default: { miniVersion: '', maxVersion: '' },
    belongTo: 'groupSetting',
    section: 'content',
  },

  // Publish Info面板 - 发布信息
  publishTime: { type: 'string', default: '', belongTo: 'publishInfo', section: 'content' },
  expireTime: { type: 'string', default: '', belongTo: 'publishInfo', section: 'content' },
};

/**
 * Style章节的必需公共字段
 * Component Style是Style章节的标准面板
 */
const REQUIRED_STYLE_FIELDS = {
  // Component Style面板 - 布局属性
  topMargin: { type: 'string', default: '0', belongTo: 'componentStyle', section: 'style' },
  bottomMargin: { type: 'string', default: '0', belongTo: 'componentStyle', section: 'style' },
  horizontalOutterMargin: { type: 'string', default: '0', belongTo: 'componentStyle', section: 'style' },
  topPadding: { type: 'string', default: '16', belongTo: 'componentStyle', section: 'style' },
  bottomPadding: { type: 'string', default: '16', belongTo: 'componentStyle', section: 'style' },
  horizontalInnerPadding: { type: 'string', default: '16', belongTo: 'componentStyle', section: 'style' },

  // Component Style面板 - 背景属性
  hasBg: { type: 'Y|N', default: 'N', belongTo: 'componentStyle', section: 'style' },
  bgType: { type: 'enum', values: ['Color', 'Image'], default: 'Color', belongTo: 'componentStyle', section: 'style' },
  bgColor: { type: 'string', default: '#ffffff', belongTo: 'componentStyle', section: 'style' },
  bgColorOpacity: { type: 'number', default: 100, belongTo: 'componentStyle', section: 'style' },
  bgImg: {
    type: 'imageObject',
    structure: '{src: "", width: 0, height: 0}',
    belongTo: 'componentStyle',
    section: 'style',
  },

  // Component Style面板 - 边框属性（可选但常见）
  cornerRadius: { type: 'string', default: '8', belongTo: 'componentStyle', section: 'style' },
  borderRadius: { type: 'string', default: '8', belongTo: 'componentStyle', section: 'style' },
};

/**
 * 面板归属映射
 * 用于生成EditFields时确定belongTo属性
 */
const FIELD_PANEL_MAPPING = {
  // header面板
  visible: 'header',

  // basicInfo面板
  title: 'basicInfo',
  showTitleBar: 'basicInfo',
  showMore: 'basicInfo',
  moreText: 'basicInfo',

  // titleStyle面板
  titleColor: 'titleStyle',
  titleColorOpacity: 'titleStyle',
  titleFontSize: 'titleStyle',
  titleFontWeight: 'titleStyle',
  isTitleFontBold: 'titleStyle',
  isTitleFontItalic: 'titleStyle',
  isTitleFontUnderline: 'titleStyle',
  titleLineHeight: 'titleStyle',
  titlePosition: 'titleStyle',
  titleIconPosition: 'titleStyle',

  // staticTextStyle面板
  staticTitleFontColor: 'staticTextStyle',
  staticTitleFontColorOpacity: 'staticTextStyle',
  staticTitleFontSize: 'staticTextStyle',
  isStaticTitleFontBold: 'staticTextStyle',
  isStaticTitleFontItalic: 'staticTextStyle',

  // componentStyle面板
  topMargin: 'componentStyle',
  bottomMargin: 'componentStyle',
  horizontalOutterMargin: 'componentStyle',
  topPadding: 'componentStyle',
  bottomPadding: 'componentStyle',
  horizontalInnerPadding: 'componentStyle',
  hasBg: 'componentStyle',
  bgType: 'componentStyle',
  bgColor: 'componentStyle',
  bgColorOpacity: 'componentStyle',
  bgImg: 'componentStyle',
  cornerRadius: 'componentStyle',
  borderRadius: 'componentStyle',
  borderColor: 'componentStyle',
  borderColorOpacity: 'componentStyle',

  // groupSetting面板
  groupSetting: 'groupSetting',
  profileSetting: 'groupSetting',
  targetLabel: 'groupSetting',
  needLogin: 'groupSetting',
  androidValue: 'groupSetting',
  iosValue: 'groupSetting',

  // publishInfo面板
  publishTime: 'publishInfo',
  expireTime: 'publishInfo',

  // eventReportSetting面板
  floorName: 'eventReportSetting',
};

// ========== 核心验证和纠正逻辑 ==========

class FieldValidator {
  constructor() {
    this.errors = [];
    this.warnings = [];
    this.corrections = [];
    this.addedFields = [];
  }

  /**
   * 验证并纠正单个字段
   */
  validateAndCorrectField(fieldName, fieldDef) {
    let correctedField = { ...fieldDef };
    let correctedName = fieldName;

    // 1. 检查并纠正字段名称
    if (FIELD_NAME_MAPPING[fieldName]) {
      const correctName = FIELD_NAME_MAPPING[fieldName];
      this.corrections.push({
        type: 'name',
        original: fieldName,
        corrected: correctName,
        reason: `标准命名规范：${fieldName} → ${correctName}`,
      });
      correctedName = correctName;
    }

    // 2. 检查并纠正数据类型
    const typeRule = FIELD_TYPE_RULES[correctedName];
    if (typeRule) {
      const originalType = this.extractType(fieldDef);
      const correctType = this.formatType(typeRule);

      if (originalType !== correctType) {
        this.corrections.push({
          type: 'dataType',
          field: correctedName,
          original: originalType,
          corrected: correctType,
          reason: `数据类型规范：${originalType} → ${correctType}`,
        });
        correctedField.type = correctType;

        // 如果有结构定义，添加说明
        if (typeRule.structure) {
          correctedField.structure = typeRule.structure;
        }
      }

      // 添加默认值
      if (typeRule.default !== undefined && !correctedField.default) {
        correctedField.default = typeRule.default;
      }
    }

    // 3. 检查配套字段
    if (FIELD_PAIRING_RULES[correctedName]) {
      const requiredPairs = FIELD_PAIRING_RULES[correctedName];
      requiredPairs.forEach((pairField) => {
        if (!this.allFields[pairField]) {
          this.addedFields.push({
            name: pairField,
            type: FIELD_TYPE_RULES[pairField],
            reason: `配套字段：${correctedName} 需要配套 ${pairField}`,
          });
        }
      });
    }

    // 4. 检查面板归属
    const belongTo = FIELD_PANEL_MAPPING[correctedName];
    if (belongTo && !correctedField.belongTo) {
      correctedField.belongTo = belongTo;
    }

    return { name: correctedName, definition: correctedField };
  }

  /**
   * 提取字段类型字符串
   */
  extractType(fieldDef) {
    if (typeof fieldDef === 'string') {
      // 从 "[String]" 格式提取
      const match = fieldDef.match(/\[([^\]]+)\]/);
      return match ? match[1].toLowerCase() : 'string';
    }
    if (fieldDef.type) {
      return fieldDef.type;
    }
    return 'unknown';
  }

  /**
   * 格式化类型定义
   */
  formatType(typeRule) {
    if (typeRule.type === 'boolean') return 'boolean';
    if (typeRule.type === 'Y|N') return "'Y'|'N'";
    if (typeRule.type === 'string') return 'string';
    if (typeRule.type === 'number') return 'number';
    if (typeRule.type === 'array') return 'array';
    if (typeRule.type === 'object') return 'object';
    if (typeRule.type === 'imageArray') return 'Array<ImageObject>';
    if (typeRule.type === 'imageObject') return 'ImageObject';
    if (typeRule.type === 'enum' && typeRule.values) {
      return typeRule.values.map((v) => `'${v}'`).join('|');
    }
    return typeRule.type;
  }

  /**
   * 检查必需的公共字段
   */
  checkRequiredFields(fields) {
    const missingFields = [];

    // 检查Content章节的必需字段
    Object.entries(REQUIRED_CONTENT_FIELDS).forEach(([fieldName, fieldDef]) => {
      if (!fields[fieldName]) {
        missingFields.push({
          name: fieldName,
          ...fieldDef,
          reason: `必需的Content公共字段 (${fieldDef.belongTo}面板)`,
        });
      }
    });

    // 检查Style章节的必需字段
    Object.entries(REQUIRED_STYLE_FIELDS).forEach(([fieldName, fieldDef]) => {
      if (!fields[fieldName]) {
        missingFields.push({
          name: fieldName,
          ...fieldDef,
          reason: `必需的Style公共字段 (${fieldDef.belongTo}面板)`,
        });
      }
    });

    return missingFields;
  }

  /**
   * 生成验证报告
   */
  generateReport() {
    return {
      summary: {
        totalErrors: this.errors.length,
        totalWarnings: this.warnings.length,
        totalCorrections: this.corrections.length,
        totalAddedFields: this.addedFields.length,
      },
      errors: this.errors,
      warnings: this.warnings,
      corrections: this.corrections,
      addedFields: this.addedFields,
      timestamp: new Date().toISOString(),
    };
  }
}

// ========== 文档解析和生成 ==========

/**
 * 解析方案文档，提取字段定义
 */
function parseDocument(content) {
  const fields = {};
  const lines = content.split('\n');

  let inContentSection = false;
  let inStyleSection = false;
  let fieldCount = 0;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];

    // 检测章节 - 处理可能的Markdown格式化
    // 实际格式可能是 "Content **可****配****置****内****容**"
    if (
      line.includes('Content') &&
      (line.includes('可配置内容') || (line.includes('可') && line.includes('配') && line.includes('置')))
    ) {
      inContentSection = true;
      inStyleSection = false;
      continue;
    }
    if (
      line.includes('Style') &&
      (line.includes('可配置内容') || (line.includes('可') && line.includes('配') && line.includes('置')))
    ) {
      inContentSection = false;
      inStyleSection = true;
      continue;
    }
    if (line.startsWith('##') && !line.startsWith('###')) {
      inContentSection = false;
      inStyleSection = false;
    }

    // 解析字段定义
    if ((inContentSection || inStyleSection) && line.includes('○')) {
      const cleanLine = line.trim();

      // 更宽松的正则：允许冒号前后有更多空格
      const match = cleanLine.match(/○\s*(\w+)\s*:\s*\[([^\]]+)\](.*)/);
      if (match) {
        const fieldName = match[1];
        const fieldType = match[2];
        const description = match[3].trim();

        fields[fieldName] = {
          type: fieldType,
          description: description,
          section: inContentSection ? 'content' : 'style',
        };
        fieldCount++;
      }
    }
  }

  return fields;
}

/**
 * 生成纠正后的文档
 */
function generateCorrectedDocument(originalContent, correctedFields, addedFields, report) {
  let content = originalContent;

  // 创建字段替换映射
  const replacements = new Map();

  // 收集所有需要替换的内容
  report.corrections.forEach((correction) => {
    if (correction.type === 'name') {
      // 替换字段名称
      const regex = new RegExp(`○\\s+${correction.original}:`, 'g');
      content = content.replace(regex, `○ ${correction.corrected}:`);
    } else if (correction.type === 'dataType') {
      // 替换数据类型
      const regex = new RegExp(`○\\s+${correction.field}:\\s*\\[[^\\]]+\\]`, 'g');
      content = content.replace(regex, (match) => {
        return match.replace(/\[[^\]]+\]/, `[${correction.corrected}]`);
      });
    }
  });

  // 收集所有字段（原有的+新增的）
  const allFields = { ...correctedFields };
  addedFields.forEach(field => {
    allFields[field.name] = field;
  });

  // 识别需要合并到Component Style的分组
  // 这些分组名称是PB系统中常见的，但可能因文档而异
  const potentialComponentStyleGroups = [
    '组件背景和边框',
    '组件的Padding',
    '组件的背景',
    '组件背景',
    '组件边框',
    '组件样式',
    'Component Style'
  ];

  // 收集这些分组中的所有字段
  const collectedStyleFields = {};
  const removedGroups = [];

  potentialComponentStyleGroups.forEach(groupName => {
    // 构建匹配该分组的正则
    const pattern = new RegExp(`●\\s*${groupName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[：:]*[\\s\\S]*?(?=●|###|##|\\n\\n)`, 'g');
    const matches = content.match(pattern);

    if (matches) {
      removedGroups.push(groupName);
      matches.forEach(match => {
        // 提取该分组中的所有字段 - 支持多种格式
        // 匹配形如 "○ fieldName: [Type] description" 或 "○ fieldName: [Type]description"
        const fieldMatches = [...match.matchAll(/○\s+(\w+):\s*\[([^\]]+)\]\s*([^\n]*)/g)];
        fieldMatches.forEach(fieldMatch => {
          const fieldName = fieldMatch[1];
          const fieldType = fieldMatch[2];
          const fieldDesc = fieldMatch[3].trim();

          // 存储字段信息供后续使用
          if (!collectedStyleFields[fieldName]) {
            collectedStyleFields[fieldName] = {
              type: fieldType,
              description: fieldDesc,
              section: 'style',
              belongTo: 'componentStyle'
            };
          }
        });
      });

      // 移除原分组，但保留Style章节标题
      content = content.replace(pattern, (match, offset) => {
        // 检查是否这个分组之前是Style章节标题
        const beforeContent = content.substring(Math.max(0, offset - 50), offset);
        if (beforeContent.includes('### Style')) {
          return '\n'; // 保留一个空行，避免删除章节标题
        }
        return '';
      });
    }
  });

  // 将收集到的Component Style字段合并到allFields
  Object.entries(collectedStyleFields).forEach(([fieldName, field]) => {
    if (!allFields[fieldName]) {
      allFields[fieldName] = field;
    }
  });

  // 重新组织字段 - 按正确的面板分组
  const contentPanels = {};
  const stylePanels = {};

  Object.entries(allFields).forEach(([fieldName, field]) => {
    // 确定字段归属
    const belongTo = field.belongTo || FIELD_PANEL_MAPPING[fieldName];
    const section = field.section ||
                    (REQUIRED_CONTENT_FIELDS[fieldName] ? 'content' :
                     REQUIRED_STYLE_FIELDS[fieldName] ? 'style' :
                     belongTo === 'componentStyle' ? 'style' : 'content');

    if (section === 'style') {
      const panelName = belongTo || 'componentStyle';
      if (!stylePanels[panelName]) {
        stylePanels[panelName] = [];
      }
      stylePanels[panelName].push({ name: fieldName, ...field });
    } else if (section === 'content') {
      const panelName = belongTo || 'basicInfo';
      if (!contentPanels[panelName]) {
        contentPanels[panelName] = [];
      }
      contentPanels[panelName].push({ name: fieldName, ...field });
    }
  });

  // 生成完整的Style章节内容（替换原有的分散内容）
  let styleReplacementText = '';

  // 特别处理Component Style面板 - 确保所有相关字段都在一起
  if (stylePanels['componentStyle']) {
    console.log(`   Component Style面板包含 ${stylePanels['componentStyle'].length} 个字段`);
    styleReplacementText = '\n● Component Style（组件样式）：\n';

    // 定义Component Style字段的显示顺序
    const componentStyleOrder = [
      // Padding相关
      'topPadding', 'bottomPadding', 'horizontalInnerPadding',
      // Margin相关
      'topMargin', 'bottomMargin', 'horizontalOutterMargin',
      // 背景相关
      'hasBg', 'bgType', 'bgColor', 'bgColorOpacity', 'bgImg',
      // 边框相关
      'cornerRadius', 'borderRadius', 'borderColor', 'borderColorOpacity'
    ];

    // 按顺序输出字段
    const processedFields = new Set();
    componentStyleOrder.forEach(fieldName => {
      const field = stylePanels['componentStyle'].find(f => f.name === fieldName);
      if (field) {
        styleReplacementText += `    ○ ${field.name}: [${formatType(field)}] ${
          field.description || getFieldDescription(field)
        }\n`;
        processedFields.add(fieldName);
      }
    });

    // 输出其他未在顺序列表中的字段
    stylePanels['componentStyle'].forEach(field => {
      if (!processedFields.has(field.name)) {
        styleReplacementText += `    ○ ${field.name}: [${formatType(field)}] ${
          field.description || getFieldDescription(field)
        }\n`;
      }
    });
  }

  // 添加其他Style面板
  Object.entries(stylePanels).forEach(([panelName, fields]) => {
    if (panelName !== 'componentStyle') {
      const panelTitle = getPanelTitle(panelName);
      styleReplacementText += `\n● ${panelTitle}：\n`;
      fields.forEach((field) => {
        styleReplacementText += `    ○ ${field.name}: [${formatType(field)}] ${
          field.description || getFieldDescription(field)
        }\n`;
      });
    }
  });

  // 查找Style章节并插入Component Style内容
  const styleStart = content.indexOf('### Style 可配置内容');
  const nextSectionStart = content.indexOf('\n##', styleStart + 1);

  console.log(`   Style章节位置: ${styleStart}, 下一节位置: ${nextSectionStart}`);

  if (styleStart !== -1) {
    // 获取Style章节的原有内容
    const styleEndPos = nextSectionStart !== -1 ? nextSectionStart : content.length;
    const styleSection = content.substring(styleStart, styleEndPos);

    // 保留原有的非Component Style相关内容
    let preservedContent = '';
    const preservePatterns = [
      /●\s*标题栏样式[：:]*[\s\S]*?(?=●|###|##|\n\n|$)/g,
      /●\s*折线图样式[：:]*[\s\S]*?(?=●|###|##|\n\n|$)/g,
      /●\s*Title Style[：:]*[\s\S]*?(?=●|###|##|\n\n|$)/g,
      /●\s*Chart Style[：:]*[\s\S]*?(?=●|###|##|\n\n|$)/g,
    ];

    preservePatterns.forEach(pattern => {
      const matches = styleSection.match(pattern);
      if (matches) {
        matches.forEach(match => {
          // 清理末尾多余的空行
          preservedContent += match.replace(/\n+$/, '\n');
        });
      }
    });

    // 构建新的Style章节 - Component Style放在最后
    const newStyleSection = '### Style 可配置内容\n' + preservedContent + styleReplacementText + '\n';

    console.log(`   Style章节替换文本长度: ${styleReplacementText.length} 字符`);

    // 替换整个Style章节
    content = content.substring(0, styleStart) + newStyleSection + content.substring(styleEndPos);
  }

  // 生成Content章节的补充字段
  let contentFieldsText = '';
  if (Object.keys(contentPanels).length > 0) {
    Object.entries(contentPanels).forEach(([panelName, fields]) => {
      // 跳过已存在的面板
      if (content.includes(`● ${getPanelTitle(panelName)}`)) {
        return;
      }
      const panelTitle = getPanelTitle(panelName);
      contentFieldsText += `\n● ${panelTitle}：\n`;
      fields.forEach((field) => {
        contentFieldsText += `    ○ ${field.name}: [${formatType(field)}] ${
          field.description || getFieldDescription(field)
        }\n`;
      });
    });

    // 在Content章节末尾添加新字段
    if (contentFieldsText) {
      content = content.replace(/### Style 可配置内容/, contentFieldsText + '\n### Style 可配置内容');
    }
  }

  // 添加纠正报告摘要
  const reportSummary = `
# 字段纠正报告

生成时间：${new Date().toISOString()}

## 纠正统计
- 字段名称纠正：${report.corrections.filter((c) => c.type === 'name').length} 项
- 数据类型纠正：${report.corrections.filter((c) => c.type === 'dataType').length} 项
- 新增必需字段：${report.addedFields.length} 项

## 主要纠正内容

### 字段命名纠正
${report.corrections
  .filter((c) => c.type === 'name')
  .map((c) => `- ${c.original} → ${c.corrected}`)
  .join('\n')}

### 数据类型纠正
${report.corrections
  .filter((c) => c.type === 'dataType')
  .map((c) => `- ${c.field}: ${c.original} → ${c.corrected}`)
  .join('\n')}

### 新增必需字段
${report.addedFields.map((f) => `- ${f.name}: ${f.type || 'string'} (${f.reason})`).join('\n')}

---

`;

  // 在文档开头插入报告
  content = reportSummary + content;

  return content;
}

/**
 * 获取面板标题
 */
function getPanelTitle(panelName) {
  const panelTitles = {
    header: '可见性控制',
    eventReportSetting: 'Event Report Setting',
    groupSetting: 'Visibility Rules（分组设置）',
    publishInfo: 'Effective Setting（发布信息）',
    basicInfo: 'Basic Info（基础信息）',
    componentStyle: 'Component Style（组件样式）',
    titleStyle: 'Title Style（标题样式）',
    staticTextStyle: 'Static Text Style（静态文本样式）',
    cardStyle: 'Card Style（卡片样式）',
  };
  return panelTitles[panelName] || panelName;
}

/**
 * 格式化字段类型
 */
function formatType(field) {
  if (field.type === 'Y|N') return "'Y'|'N'";
  if (field.type === 'imageObject') return 'Object';
  if (field.type === 'imageArray') return 'Array<Object>';
  if (field.type === 'enum' && field.values) {
    return field.values.map((v) => `'${v}'`).join('|');
  }
  return field.type || 'string';
}

/**
 * 获取字段描述
 */
function getFieldDescription(field) {
  const descriptions = {
    visible: '组件是否可见',
    floorName: '楼层名称（用于事件埋点）',
    groupSetting: '用户组设置',
    profileSetting: '用户档案设置',
    targetLabel: '目标标签',
    needLogin: '是否需要登录',
    androidValue: 'Android版本限制',
    iosValue: 'iOS版本限制',
    publishTime: '发布开始时间',
    expireTime: '发布结束时间',
    topMargin: '组件顶部外边距',
    bottomMargin: '组件底部外边距',
    horizontalOutterMargin: '组件水平外边距',
    topPadding: '组件顶部内边距',
    bottomPadding: '组件底部内边距',
    horizontalInnerPadding: '组件水平内边距',
    hasBg: '是否有背景',
    bgType: '背景类型（颜色或图片）',
    bgColor: '背景颜色',
    bgColorOpacity: '背景颜色透明度',
    bgImg: '背景图片',
    cornerRadius: '圆角大小',
    borderRadius: '边框圆角',
  };
  return descriptions[field.name] || '';
}

// ========== 主执行函数 ==========

function main() {
  const args = process.argv.slice(2);

  if (args.length < 1) {
    console.log(`
使用方法：
  node scripts/validate-and-correct-fields.js <方案文档路径>

示例：
  node scripts/validate-and-correct-fields.js "Usage Trends2 组件生成相关资料/Usage Trends 方案文档.md"

输出：
  - 纠正后的文档：<原文件名>-corrected.md
  - 纠正报告：<原文件名>-correction-report.json
    `);
    process.exit(1);
  }

  const inputFile = args[0];
  const inputPath = path.resolve(inputFile);

  if (!fs.existsSync(inputPath)) {
    console.error(`错误：文件不存在 - ${inputPath}`);
    process.exit(1);
  }

  console.log('\n========== 字段规范验证和纠正工具 ==========\n');
  console.log(`输入文件：${inputFile}`);

  // 读取文档
  const content = fs.readFileSync(inputPath, 'utf8');

  // 解析字段定义
  console.log('\n1. 解析方案文档...');
  console.log('   搜索字段定义...');
  const fields = parseDocument(content);
  console.log(`   总计找到 ${Object.keys(fields).length} 个字段定义`);

  // 创建验证器
  const validator = new FieldValidator();
  validator.allFields = fields;

  // 验证并纠正字段
  console.log('\n2. 验证字段规范...');
  const correctedFields = {};

  Object.entries(fields).forEach(([fieldName, fieldDef]) => {
    const corrected = validator.validateAndCorrectField(fieldName, fieldDef);
    correctedFields[corrected.name] = corrected.definition;
  });

  // 检查必需的公共字段
  console.log('\n3. 检查必需的公共字段...');
  const missingFields = validator.checkRequiredFields(correctedFields);
  validator.addedFields.push(...missingFields);
  console.log(`   缺失 ${missingFields.length} 个必需字段`);

  // 生成报告
  const report = validator.generateReport();

  // 输出验证结果
  console.log('\n========== 验证结果 ==========\n');
  console.log(`✓ 字段名称纠正：${report.corrections.filter((c) => c.type === 'name').length} 项`);
  console.log(`✓ 数据类型纠正：${report.corrections.filter((c) => c.type === 'dataType').length} 项`);
  console.log(`✓ 新增必需字段：${report.addedFields.length} 项`);

  if (report.corrections.length > 0) {
    console.log('\n主要纠正内容：');
    report.corrections.slice(0, 10).forEach((c) => {
      if (c.type === 'name') {
        console.log(`  • 字段名称：${c.original} → ${c.corrected}`);
      } else if (c.type === 'dataType') {
        console.log(`  • 数据类型：${c.field}: ${c.original} → ${c.corrected}`);
      }
    });
    if (report.corrections.length > 10) {
      console.log(`  ... 还有 ${report.corrections.length - 10} 项纠正`);
    }
  }

  // 生成纠正后的文档
  console.log('\n4. 生成纠正后的文档...');
  const correctedContent = generateCorrectedDocument(content, correctedFields, validator.addedFields, report);

  // 保存文件
  const outputDir = path.dirname(inputPath);
  const baseName = path.basename(inputPath, '.md');
  const correctedPath = path.join(outputDir, `${baseName}-corrected.md`);
  const reportPath = path.join(outputDir, `${baseName}-correction-report.json`);

  fs.writeFileSync(correctedPath, correctedContent);
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));

  console.log(`\n✓ 纠正后的文档已保存：${correctedPath}`);
  console.log(`✓ 详细报告已保存：${reportPath}`);

  // 如果有严重错误，返回非零退出码
  if (report.errors.length > 0) {
    console.log('\n⚠️ 发现严重错误，请查看报告文件了解详情');
    process.exit(1);
  }

  console.log('\n✓ 字段验证和纠正完成！');
  console.log('\n建议：');
  console.log('1. 查看纠正后的文档，确认自动纠正是否正确');
  console.log('2. 根据报告中的建议，手动调整特殊业务字段');
  console.log('3. 使用纠正后的文档执行AI生成任务');
}

// 执行主函数
main();
